(function($, doc) {
    // 如果支持沉浸式状态栏，则为相应元素添加immersion类
    app.immersion(function() {
        doc.querySelector('header').classList.add('immersion');
    });

    $.init({
        statusBarBackground: app.getThemeColor(),
        preloadPages: [{
            id: 'outerlink',
            url: 'outerlink.html'
        }/*, {
            id: 'normal',
            url: 'normal.html'
        }*/]
    });

    $.plusReady(function() {
        // 锁定为竖屏
        $.os.plus && plus.screen.lockOrientation("portrait-primary");

        var settings = app.getSettings();
        var state = app.getState();
        var mainPage = $.preload({
            "id": 'main',
            "url": 'main.html'
        });

        var toMain = function() {
            $.fire(mainPage, 'show', null);
            $.openWindow({
                id: 'main',
                url: 'main.html'
            });
        }

        //检查 "登录状态/锁屏状态" 开始
        if (settings.autoLogin && state.token && settings.gestures) {
            $.openWindow({
                url: 'unlock.html',
                id: 'unlock'
            });
        } else if (settings.autoLogin && state.token) {
            toMain();
        } else {
            app.setState(null);
            //第三方登录
            var authBtns = ['qihoo', 'weixin', 'sinaweibo', 'qq']; //配置业务支持的第三方登录
            var auths = {};
            var oauthArea = doc.querySelector('.oauth-area');
            $.os.plus && plus.oauth.getServices(function(services) {
                for (var i in services) {
                    var service = services[i];
                    auths[service.id] = service;
                    if (~authBtns.indexOf(service.id)) {
                        var isInstalled = app.isInstalled(service.id);
                        var btn = document.createElement('div');
                        //如果微信未安装，则为不启用状态
                        btn.setAttribute('class', 'oauth-btn' + (!isInstalled && service.id === 'weixin' ? (' disabled') : ''));
                        btn.authId = service.id;
                        btn.style.backgroundImage = 'url("images/' + service.id + '.png")'
                        oauthArea.appendChild(btn);
                    }
                }
                $(oauthArea).on('tap', '.oauth-btn', function() {
                    if (this.classList.contains('disabled')) {
                        plus.nativeUI.toast('您尚未安装微信客户端');
                        return;
                    }
                    var auth = auths[this.authId];
                    var waiting = plus.nativeUI.showWaiting();
                    auth.login(function() {
                        waiting.close();
                        plus.nativeUI.toast("登录认证成功");
                        auth.getUserInfo(function() {
                            plus.nativeUI.toast("获取用户信息成功");
                            var name = auth.userInfo.nickname || auth.userInfo.name;
                            app.createState(name, function() {
                                toMain();
                            });
                        }, function(e) {
                            plus.nativeUI.toast("获取用户信息失败：" + e.message);
                        });
                    }, function(e) {
                        waiting.close();
                        plus.nativeUI.toast("登录认证失败：" + e.message);
                    });
                });
            }, function(e) {
                oauthArea.style.display = 'none';
                plus.nativeUI.toast("获取登录认证失败：" + e.message);
            });
        }
        // close splash
        setTimeout(function() {
            //关闭 splash
            $.os.plus && plus.navigator.closeSplashscreen();
        }, 600);

        //检查 "登录状态/锁屏状态" 结束
        var accountBox = $get('account');
        var passwordBox = $get('password');

        $get('login').on('tap', function(event) {
            var loginInfo = {
                account: accountBox.value || 'admin',
                password: passwordBox.value || '123456'
            }
            toMain();
            /*app.login(loginInfo, function(err) {
                if (err) {
                    plus.nativeUI.toast(err);
                    return;
                }
                toMain();
            });*/
        });

        // 自动登录开关
        var auto_login_btn = $get("autoLogin");
        auto_login_btn.classList[settings.autoLogin ? 'add' : 'remove']('mui-active')
        auto_login_btn.on('toggle', function(event) {
            setTimeout(function() {
                var isActive = event.detail.isActive;
                settings.autoLogin = isActive;
                app.setSettings(settings);
            }, 50);
        });

        $get('reg').on('tap', function(event) {
            $.openWindow({
                url: 'reg.html',
                id: 'reg',
                preload: true
            });
        });

        $get('forgetPassword').on('tap', function(event) {
            $.openWindow({
                url: 'forget_password.html',
                id: 'forget_password',
                preload: true
            });
        });

        // 打开键盘的时候，隐藏第三方登录图标
        window.addEventListener('resize', function() {
            oauthArea.style.display = document.body.clientHeight > 400 ? 'block' : 'none';
        }, false);

        app.doubletapExit();
    });
}(mui, document));